package com.jianganming.nio.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class FileClient {
    private SocketChannel socketChannel;

    public FileClient(){
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
            socketChannel.configureBlocking(false);
        }catch (Exception e){

        }
    }

    public void sendInfo(String path){
        try {
            File file = new File(path);
            FileInputStream in = new FileInputStream(file);
            FileChannel fileChannel = in.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int num = 0;
            while ((num=fileChannel.read(buffer)) > 0) {
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
            }
            if (num == -1) {
                fileChannel.close();
                socketChannel.shutdownOutput();
            }

        }catch (Exception e){
            System.out.println("发送失败");
        }finally {
            try {
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    public static void main(String[] args) {
        FileClient chatClient = new FileClient();
        chatClient.sendInfo("/Users/jianganming/Downloads/RabbitMQ.pdf");

    }
}
